import {
  Form,
  ImageViewer,
  NavBar,
  Swiper,
  Picker,
  Button,
  Toast,
  Empty,
  Input,
  Popup,
  List,
} from "antd-mobile";
import { useEffect, useRef, useState } from "react";
import styles from "./index.module.css";
import { useNavigate } from "react-router-dom";
import { Image } from "antd-mobile";
import { Select } from "antd";
import { ClockCircleOutline } from "antd-mobile-icons";
import request from "../../axios";

const basicColumn = [
  [
    { label: "优秀", value: "4" },
    { label: "良好", value: "3" },
    { label: "及格", value: "2" },
    { label: "不及格", value: "1" },
    { label: "待评估", value: "0" },
  ],
];

const Check = () => {
  const ref = useRef<any>(null);
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [visible, setVisible] = useState(false);

  const [nowImg, setNowImg] = useState<string>("");
  const [pages, setPages] = useState<number>(1);
  const [datas, setData] = useState<any[]>([]);
  const [cook, setCook] = useState<any[]>([]);
  const [startX, setStartX] = useState(0);

  const [nowIndex, setNowIndex] = useState<any>(0);
  const [nowPj, setNowPj] = useState<any>("0");
  const [nowId, setNowId] = useState<any>("");
  
  // 菜品标签相关状态
  const [tagVisible, setTagVisible] = useState<boolean>(false);
  const [hisList, setHisList] = useState<any[]>([]);
  const [nowTags, setNowTags] = useState<string>("");
  const handleTouchStart = (e: any) => {
    setStartX(e.touches[0].clientX);
  };

  const handleTouchEnd = (e: any) => {
    const endX = e.changedTouches[0].clientX;
    if (startX - endX > 80) {
      ref.current?.swipeNext();
    }
  };

  const getDataList = async (page: number = 1, isMore = false) => {
    const { data } = await request.get("/meal_record/list/unEvaluated", {
      pageNo: page,
      pageSize: 5,
    });
    if (data) {
      // data.records = data.records.filter((item:any,ind:any)=>{
      //     return ind!==0 && ind!==1 && ind!==2
      // })
      if (isMore) {
        setData([...datas, ...data?.records]);
      } else {
        setData(data?.records || []);
        setNowId(data?.records?.[0]?.dishId || "");
        setNowImg(data?.records?.[0].dishPicture);
        form.setFieldsValue({
          dishName: data?.records?.[0]?.dishId
            ? String(data?.records?.[0]?.dishId)
            : null,
          personEvaluate: ["0"],
          tags: "", // 初始化标签
        });
        setNowTags(""); // 初始化标签状态
      }
    }
  };

  const getCookList = async (page: number = 1) => {
    const { data } = await request.get("/dish/list/all", {
      name: null,
    });
    if (data) {
      setCook(data?.dishList || []);
    }
  };

  // 获取历史标签
  const getIdList = async () => {
    try {
      if (!nowId) {
        Toast.show("请选择菜品");
        setHisList([]);
        return;
      }
      const { data } = await request.get(`/dish_tag/${nowId}`);
      if (data) {
        setHisList(data);
      }
      setTagVisible(true);
    } catch (error) {}
  };

  // 设置标签
  const setTags = (item: string) => {
    const tags = form.getFieldValue("tags") || "";
    const newTags = tags + "#" + item;
    form.setFieldValue("tags", newTags);
    setNowTags(newTags);
    setTagVisible(false);
  };

  const handleChange = async (id: any) => {
    try {
      await request.post("/meal_record/score", {
        id,
        dishId: nowId,
        personEvaluate: nowPj,
        tags: nowTags, // 添加标签数据
      });
      Toast.show("评价成功");
      ref.current?.swipeNext();
      // 清空当前标签
      setNowTags("");
      form.setFieldValue("tags", "");
    } catch (error) {}
  };

  useEffect(() => {
    getDataList(1);
    getCookList();
  }, []);

  return (
    <>
      <ImageViewer
        classNames={{
          mask: "customize-mask",
          body: "customize-body",
        }}
        image={nowImg}
        visible={visible}
        onClose={() => {
          setVisible(false);
        }}
      />
      <div
        onTouchStart={handleTouchStart}
        onTouchEnd={handleTouchEnd}
        className={styles.all}
      >
        <NavBar
          onBack={() => {
            navigate("/mine");
          }}
          className={styles.top}
        >
          菜品评分
        </NavBar>
        {datas?.length ? (
          <Swiper
            tabIndex={nowIndex}
            onIndexChange={(e) => {
              if (e % 4 === 0) {
                getDataList(pages + 1, true);
                setPages(pages + 1);
              }
              setNowImg(datas[e].dishPicture);
              setNowIndex(e);
              setNowPj("0");
              setNowId(datas[e].dishId || null);
              setNowTags(""); // 重置标签
              form.setFieldsValue({
                dishName: datas[e].dishId ? String(datas[e].dishId) : null,
                personEvaluate: ["0"],
                tags: "", // 重置标签表单值
              });
            }}
            className={styles.swpier}
            allowTouchMove={false}
            ref={ref}
          >
            {datas.map((item) => {
              return (
                <Swiper.Item key={item}>
                  <div
                    style={{
                      width: "100%",
                      height: "100%",
                      display: "flex",
                      flexDirection: "column",
                    }}
                  >
                    <Image
                      src={item.dishPicture}
                      style={{
                        borderRadius: 10,
                        width: "100%",
                        height: "fit-content",
                      }}
                      onClick={() => setVisible(true)}
                    />
                    <Form layout="horizontal" form={form}>
                      <Form.Item
                        name="dishName"
                        label="菜品名称"
                        className={styles.input_title}
                      >
                        <Select
                          style={{ width: "100%" }}
                          showSearch
                          optionFilterProp="label"
                          // value={'225'}
                          defaultValue={String(nowId)}
                          onSelect={(e) => {
                            setNowId(e);
                          }}
                          options={cook.map((item) => {
                            return {
                              value: String(item.id),
                              label: item.name,
                            };
                          })}
                        />
                      </Form.Item>
                      <Form.Item
                        name="personEvaluate"
                        label="菜品分数"
                        className={styles.input_title}
                        trigger="onConfirm"
                        onClick={(e, datePickerRef: any) => {
                          datePickerRef.current?.open();
                        }}
                      >
                        <Picker
                          columns={basicColumn}
                          onConfirm={(e) => {
                            setNowPj(e[0]);
                          }}
                        >
                          {(val) => (val?.[0] ? val?.[0]?.label : "请选择分数")}
                        </Picker>
                      </Form.Item>
                      
                      {/* 菜品标签输入框 */}
                      <Form.Item
                        name="tags"
                        label="菜品标签"
                        className={styles.input_title}
                      >
                        <Input 
                          placeholder='请输入菜品标签,标签之间用"#"号隔开'
                          value={nowTags}
                          onChange={(val) => {
                            setNowTags(val);
                            form.setFieldValue("tags", val);
                          }}
                        />
                      </Form.Item>
                      
                      {/* 历史标签按钮 */}
                      <Button 
                        className={styles.button1} 
                        onClick={() => getIdList()}
                      >
                        <ClockCircleOutline />
                        <span style={{ marginLeft: 4 }}>历史标签</span>
                      </Button>
                      
                      <Form.Item>
                        <div className={styles.shopName_bottom}>
                          <Button
                            color="primary"
                            size="large"
                            className={styles.button}
                            onClick={() => handleChange(item.id)}
                          >
                            确认
                          </Button>
                        </div>
                      </Form.Item>
                    </Form>
                  </div>
                </Swiper.Item>
              );
            })}
          </Swiper>
        ) : (
          <Empty />
        )}
        
        {/* 历史标签弹窗 */}
        <Popup
          visible={tagVisible}
          onMaskClick={() => {
            setTagVisible(false);
          }}
          position="right"
          bodyStyle={{ width: "60vw" }}
        >
          {hisList?.length ? (
            <List>
              {hisList?.map((item: any, index: number) => {
                return (
                  <List.Item key={index} onClick={() => setTags(item)}>
                    {item}
                  </List.Item>
                );
              })}
            </List>
          ) : (
            <Empty
              description="暂无数据"
              style={{ width: "100%", height: "100%" }}
            />
          )}
        </Popup>
      </div>
    </>
  );
};

export default Check;
